package com.lucence.util;

import java.io.IOException;

import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.util.Version;

public class LuceneUtil {
	private static IndexWriter indexWriter;
	private static IndexSearcher indexSearcher;
	
	static {
		try {
			System.out.println("init indexWriter object");
			IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_36, Config.getAnalyzer());
			indexWriter = new IndexWriter(Config.getDirectory(),indexWriterConfig);
			
			Runtime.getRuntime().addShutdownHook(new Thread(){
				public void run(){
					closeIndexWriter();
					closeIndexSearcher();
				}
			});
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static IndexSearcher getIndexSearcher() {
		if(indexSearcher==null){
			System.out.println("get indexSearcher");
			try {
				indexSearcher = new IndexSearcher(IndexReader.open(Config.getDirectory()));
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
		return indexSearcher;
	}
	
	public static IndexWriter getIndexWriter() {
		System.out.println("getIndexWriter");
		return indexWriter;
	}
	
	public static void closeIndexWriter(){
		try {
			System.out.println("closeIndexWriter");
			if(indexWriter!=null){
				indexWriter.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void closeIndexSearcher(){
		try {
			System.out.println("closeIndexSearcher");
			if(indexSearcher!=null){
				indexSearcher.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
